import { defineStore } from 'pinia';
import { TokenManager } from '../../utils/request';

export const useUserStore = defineStore('user', {
  state: () => ({
    // 从TokenManager获取初始状态
    token: TokenManager.getAccessToken() || '',
    role: TokenManager.getUserType() || '',
    userId: TokenManager.getUserId() || '',
  }),
  
  getters: {
    // 检查是否已登录
    isLoggedIn: (state) => !!state.token,
    
    // 获取用户类型
    userType: (state) => state.role,
    
    // 获取用户ID
    currentUserId: (state) => state.userId,
  },
  
  actions: {
    // 设置用户信息
    setUser(accessToken, refreshToken, userType, userId) {
      this.token = accessToken;
      this.role = userType;
      this.userId = userId;
      
      // 使用TokenManager统一管理
      TokenManager.setTokens(accessToken, refreshToken, userType, userId);
    },
    
    // 更新token
    updateToken(accessToken, refreshToken) {
      this.token = accessToken;
      if (refreshToken) {
        // refreshToken可选更新
        TokenManager.setTokens(accessToken, refreshToken, this.role, this.userId);
      } else {
        // 只更新accessToken
        localStorage.setItem('access_token', accessToken);
        localStorage.setItem('last_activity', Date.now().toString());
      }
    },
    
    // 登出
    logout() {
      this.token = '';
      this.role = '';
      this.userId = '';
      
      // 使用TokenManager统一清除
      TokenManager.clearTokens();
    },
    
    // 从localStorage同步状态
    syncFromStorage() {
      this.token = TokenManager.getAccessToken() || '';
      this.role = TokenManager.getUserType() || '';
      this.userId = TokenManager.getUserId() || '';
    },
    
    // 检查token是否有效
    checkTokenValidity() {
      return TokenManager.isLoggedIn() && TokenManager.checkSession();
    }
  }
});